import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Container,
  Paper,
  TextField,
  Button,
  Typography,
  Box,
  Alert,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
} from '@mui/material';
import { format } from 'date-fns';

interface User {
  _id: string;
  username: string;
  role: 'user' | 'admin';
  createdAt: string;
}

const UserManagement: React.FC = () => {
  const navigate = useNavigate();
  const [users, setUsers] = useState<User[]>([]);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [openDialog, setOpenDialog] = useState(false);
  const [editUser, setEditUser] = useState<User | null>(null);
  const [userData, setUserData] = useState({
    username: '',
    password: '',
    role: 'user' as 'user' | 'admin',
  });

  useEffect(() => {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      navigate('/');
      return;
    }

    const user = JSON.parse(userStr);
    if (user.role !== 'admin') {
      navigate('/');
      return;
    }
  }, [navigate]);

  const fetchUsers = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setError('请先登录');
        return;
      }

      const response = await fetch('http://localhost:5000/api/users', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.message);
        return;
      }

      setUsers(data);
    } catch (error) {
      setError('获取用户列表失败');
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setError('请先登录');
        return;
      }

      const url = editUser
        ? `http://localhost:5000/api/users/${editUser._id}`
        : 'http://localhost:5000/api/users';

      const response = await fetch(url, {
        method: editUser ? 'PUT' : 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({
          username: userData.username,
          password: userData.password,
          role: userData.role,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.message);
        return;
      }

      setSuccess(editUser ? '用户修改成功！' : '用户创建成功！');
      setOpenDialog(false);
      setEditUser(null);
      setUserData({
        username: '',
        password: '',
        role: 'user',
      });
      fetchUsers();
    } catch (error) {
      setError('服务器连接失败');
    }
  };

  const handleEdit = (user: User) => {
    setEditUser(user);
    setUserData({
      username: user.username,
      password: '',
      role: user.role,
    });
    setOpenDialog(true);
  };

  const handleDelete = async (userId: string) => {
    if (!window.confirm('确定要删除这个用户吗？')) {
      return;
    }

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setError('请先登录');
        return;
      }

      const response = await fetch(`http://localhost:5000/api/users/${userId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        const data = await response.json();
        setError(data.message);
        return;
      }

      setSuccess('用户删除成功！');
      fetchUsers();
    } catch (error) {
      setError('删除用户失败');
    }
  };

  return (
    <Container component="main" maxWidth="lg" sx={{
      minHeight: '100vh',
      position: 'relative',
      '&::before': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, #0a192f 0%, #203a43 100%)',
        zIndex: -2,
      },
      '&::after': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        backgroundRepeat: 'repeat',
        opacity: 0.3,
        zIndex: -1,
      }
    }}>
      <Paper elevation={3} sx={{
        mt: 8,
        p: 4,
        background: 'rgba(255, 255, 255, 0.05)',
        backdropFilter: 'blur(10px)',
        borderRadius: '16px',
        border: '1px solid rgba(255, 255, 255, 0.1)'
      }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
          <Typography component="h1" variant="h5" sx={{
            color: 'white',
            fontWeight: 'bold',
            textShadow: '2px 2px 4px rgba(0,0,0,0.3)'
          }}>
            用户管理
          </Typography>
          <Button
            variant="contained"
            onClick={() => {
              setEditUser(null);
              setUserData({
                username: '',
                password: '',
                role: 'user',
              });
              setOpenDialog(true);
            }}
            sx={{
              background: 'linear-gradient(45deg, #1976d2 30%, #64b5f6 90%)',
              color: 'white',
              fontWeight: 'bold',
              '&:hover': {
                background: 'linear-gradient(45deg, #64b5f6 30%, #1976d2 90%)',
              },
            }}
          >
            添加用户
          </Button>
        </Box>

        {error && (
          <Alert severity="error" sx={{ mb: 2, bgcolor: 'rgba(211, 47, 47, 0.1)' }}>
            {error}
          </Alert>
        )}

        {success && (
          <Alert severity="success" sx={{ mb: 2, bgcolor: 'rgba(46, 125, 50, 0.1)' }}>
            {success}
          </Alert>
        )}

        <TableContainer sx={{
          background: 'rgba(255, 255, 255, 0.05)',
          borderRadius: '8px',
          '& .MuiTableCell-root': {
            color: 'white',
            borderColor: 'rgba(255, 255, 255, 0.1)',
          },
          '& .MuiTableRow-root:hover': {
            backgroundColor: 'rgba(255, 255, 255, 0.1)',
          },
        }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>用户名</TableCell>
                <TableCell>角色</TableCell>
                <TableCell>注册时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {users.map((user) => (
                <TableRow key={user._id}>
                  <TableCell>{user.username}</TableCell>
                  <TableCell>{user.role === 'admin' ? '管理员' : '普通用户'}</TableCell>
                  <TableCell>
                    {(() => {
                      try {
                        const date = new Date(user.createdAt);
                        if (isNaN(date.getTime())) {
                          return '无效日期';
                        }
                        return format(date, 'yyyy-MM-dd HH:mm');
                      } catch (error) {
                        return '无效日期';
                      }
                    })()} 
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="outlined"
                      size="small"
                      onClick={() => handleEdit(user)}
                      sx={{
                        mr: 1,
                        color: '#64b5f6',
                        borderColor: '#64b5f6',
                        '&:hover': {
                          borderColor: '#1976d2',
                          backgroundColor: 'rgba(25, 118, 210, 0.08)',
                        },
                      }}
                    >
                      编辑
                    </Button>
                    <Button
                      variant="outlined"
                      color="error"
                      size="small"
                      onClick={() => handleDelete(user._id)}
                      sx={{
                        color: '#f44336',
                        borderColor: '#f44336',
                        '&:hover': {
                          borderColor: '#d32f2f',
                          backgroundColor: 'rgba(211, 47, 47, 0.08)',
                        },
                      }}
                    >
                      删除
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>

        <Dialog
          open={openDialog}
          onClose={() => {
            setOpenDialog(false);
            setEditUser(null);
            setUserData({
              username: '',
              password: '',
              role: 'user',
            });
          }}
          maxWidth="sm"
          fullWidth
          PaperProps={{
            sx: {
              background: 'linear-gradient(135deg, #2c3e50 0%, #3498db 100%)',
              color: 'white',
              borderRadius: '16px',
            }
          }}
        >
          <DialogTitle sx={{
            textAlign: 'center',
            borderBottom: '1px solid rgba(255,255,255,0.1)'
          }}>
            {editUser ? '编辑用户' : '添加用户'}
          </DialogTitle>
          <DialogContent>
            <Box component="form" onSubmit={handleSubmit} noValidate sx={{
              mt: 2,
              '& .MuiTextField-root, & .MuiFormControl-root': {
                mb: 2,
                width: '100%',
                '& .MuiOutlinedInput-root': {
                  color: 'white',
                  '& fieldset': {
                    borderColor: 'rgba(255, 255, 255, 0.23)',
                  },
                  '&:hover fieldset': {
                    borderColor: 'rgba(255, 255, 255, 0.5)',
                  },
                  '&.Mui-focused fieldset': {
                    borderColor: '#1976d2',
                  },
                },
                '& .MuiInputLabel-root': {
                  color: 'rgba(255, 255, 255, 0.7)',
                },
                '& .MuiSelect-icon': {
                  color: 'rgba(255, 255, 255, 0.7)',
                },
              },
            }}>
              <TextField
                required
                label="用户名"
                value={userData.username}
                onChange={(e) => setUserData({ ...userData, username: e.target.value })}
              />
              <TextField
                required
                type="password"
                label={editUser ? '新密码（留空则不修改）' : '密码'}
                value={userData.password}
                onChange={(e) => setUserData({ ...userData, password: e.target.value })}
              />
              <FormControl>
                <InputLabel>角色</InputLabel>
                <Select
                  value={userData.role}
                  label="角色"
                  onChange={(e) => setUserData({ ...userData, role: e.target.value as 'user' | 'admin' })}
                >
                  <MenuItem value="user">普通用户</MenuItem>
                  <MenuItem value="admin">管理员</MenuItem>
                </Select>
              </FormControl>
            </Box>
          </DialogContent>
          <DialogActions sx={{
            borderTop: '1px solid rgba(255,255,255,0.1)',
            p: 2,
          }}>
            <Button
              onClick={() => {
                setOpenDialog(false);
                setEditUser(null);
                setUserData({
                  username: '',
                  password: '',
                  role: 'user',
                });
              }}
              sx={{
                color: 'rgba(255,255,255,0.7)',
                '&:hover': { color: 'white' }
              }}
            >
              取消
            </Button>
            <Button
              type="submit"
              variant="contained"
              onClick={handleSubmit}
              sx={{
                background: 'linear-gradient(45deg, #1976d2 30%, #64b5f6 90%)',
                color: 'white',
                fontWeight: 'bold',
                '&:hover': {
                  background: 'linear-gradient(45deg, #64b5f6 30%, #1976d2 90%)',
                },
              }}
            >
              {editUser ? '保存修改' : '确认添加'}
            </Button>
          </DialogActions>
        </Dialog>
      </Paper>
    </Container>
  );
};

export default UserManagement;